<template>
  <div class="profile">
    <van-nav-bar
      title="个人信息"
      left-arrow
      @click-left="router.back()"
    />

    <!-- 用户头像和基本信息 -->
    <div class="user-header">
      <div class="avatar-wrapper" @click="handleAvatarClick">
        <van-image
          round
          width="80"
          height="80"
          :src="baseURL + userInfo.avatar || defaultAvatar"
        />
        <van-icon name="photograph" class="camera-icon" />
      </div>
      <div class="user-info">
        <div class="name">{{ userInfo.name }}</div>
        <div class="patient-no">就诊卡号：{{ userInfo.patientNo || '未绑定' }}</div>
      </div>
    </div>

    <!-- 基本信息 -->
    <div class="section">
      <div class="section-title">基本信息</div>
      <van-cell-group inset>
        <van-cell title="姓名" :value="userInfo.name" is-link @click="showEditDialog('name')" />
        <van-cell title="性别" :value="genderText" is-link @click="showEditDialog('gender')" />
        <van-cell title="出生日期" :value="userInfo.birthday" is-link @click="showDatePicker = true" />
        <van-cell title="身份证号" :value="maskIdCard(userInfo.idCard)" />
        <van-cell title="手机号码" :value="maskPhone(userInfo.phone)" is-link @click="showEditDialog('phone')" />
      </van-cell-group>
    </div>

    <!-- 医疗信息 -->
    <div class="section">
      <div class="section-title">医疗信息</div>
      <van-cell-group inset>
        <van-cell title="血型" :value="userInfo.bloodType" is-link @click="showEditDialog('bloodType')" />
        <van-cell title="过敏史" :value="userInfo.allergies?.join('、') || '无'" is-link @click="showEditDialog('allergies')" />
        <van-cell title="既往病史" :value="userInfo.medicalHistory?.join('、') || '无'" is-link @click="showEditDialog('medicalHistory')" />
      </van-cell-group>
    </div>

    <!-- 医保信息 -->
    <div class="section">
      <div class="section-title">医保信息</div>
      <van-cell-group inset>
        <van-cell title="医保卡号" :value="userInfo.insuranceNo || '未绑定'" />
        <van-cell title="医保类型" :value="userInfo.insuranceType || '未设置'" />
        <van-cell title="参保地区" :value="userInfo.insuranceLocation || '未设置'" />
      </van-cell-group>
    </div>

    <!-- 紧急联系人 -->
    <div class="section">
      <div class="section-header">
        <span class="section-title">紧急联系人</span>
        <van-button 
          plain
          type="primary" 
          size="small"
          icon="plus"
          @click="handleAddContact"
        >
          添加
        </van-button>
      </div>
      <van-cell-group inset>
        <template v-if="userInfo.emergencyContacts?.length">
          <van-swipe-cell v-for="contact in userInfo.emergencyContacts" :key="contact.id">
            <van-cell center :title="contact.name" :label="contact.relationship">
              <template #value>
                <div class="contact-phone">{{ maskPhone(contact.phone) }}</div>
              </template>
            </van-cell>
            <template #right>
              <van-button 
                square 
                type="danger" 
                text="删除" 
                class="delete-btn"
                @click="handleDeleteContact(contact.id)"
              />
            </template>
          </van-swipe-cell>
        </template>
        <van-empty v-else description="暂无紧急联系人" />
      </van-cell-group>
    </div>

    

    <!-- 退出登录按钮 -->
    <div class="logout-wrapper">
      <van-button 
        block 
        type="primary" 
        @click="handleChangePassword"
        class="change-password-btn"
      >
        修改密码
      </van-button>
      <van-button 
        block 
        type="danger" 
        @click="handleLogout"
        :loading="logoutLoading"
        class="logout-btn"
      >
        退出登录
      </van-button>
    </div>

    <!-- 编辑弹窗 -->
    <van-dialog
      v-model="showDialog"
      :title="dialogTitle"
      show-cancel-button
      :before-close="handleDialogClose"
    >
      <div class="dialog-content">
        <!-- 文本输入 -->
        <template v-if="['name', 'phone'].includes(editField)">
          <van-field
            v-model="editValue"
            :label="dialogTitle"
            :placeholder="'请输入' + dialogTitle"
            :rules="getFieldRules(editField)"
            :formatter="getFieldFormatter(editField)"
            @blur="handleFieldBlur"
          />
        </template>

        <!-- 性别选择 -->
        <template v-if="editField === 'gender'">
          <van-radio-group v-model="editValue">
            <van-cell-group inset>
              <van-cell title="男" clickable @click="editValue = 1">
                <template #right-icon>
                  <van-radio :name="1" />
                </template>
              </van-cell>
              <van-cell title="女" clickable @click="editValue = 2">
                <template #right-icon>
                  <van-radio :name="2" />
                </template>
              </van-cell>
            </van-cell-group>
          </van-radio-group>
        </template>

        <!-- 血型选择 -->
        <template v-if="editField === 'bloodType'">
          <van-radio-group v-model="editValue">
            <van-cell-group inset>
              <van-cell 
                v-for="type in bloodTypes" 
                :key="type" 
                :title="type"
                clickable 
                @click="editValue = type"
              >
                <template #right-icon>
                  <van-radio :name="type" />
                </template>
              </van-cell>
            </van-cell-group>
          </van-radio-group>
        </template>

        <!-- 过敏史/病史编辑 -->
        <template v-if="['allergies', 'medicalHistory'].includes(editField)">
          <van-field
            v-model="editValue"
            :label="dialogTitle"
            type="textarea"
            rows="3"
            :placeholder="'请输入' + dialogTitle + '，多个项目请用逗号分隔'"
            :rules="[{ required: false }]"
          />
        </template>
      </div>
    </van-dialog>

    <!-- 日期选择器 -->
    <van-calendar
      v-model="showDatePicker"
      @confirm="handleDateConfirm"
      :min-date="minDate"
      :max-date="maxDate"
      title="选择出生日期"
      :show-confirm="false"
    />

    <!-- 添加紧急联系人弹窗 -->
    <van-dialog
      v-model="showContactDialog"
      title="添加紧急联系人"
      show-cancel-button
      :before-close="handleContactDialogClose"
    >
      <van-form @submit="handleConfirmAddContact">
        <van-cell-group inset>
          <van-field
            v-model="contactForm.name"
            name="name"
            label="姓名"
            placeholder="请输入联系人姓名"
            :rules="[{ required: true, message: '请输入联系人姓名' }]"
          />
          <van-field
            v-model="contactForm.phone"
            name="phone"
            label="手机号"
            placeholder="请输入联系人手机号"
            :rules="[
              { required: true, message: '请输入联系人手机号' },
              { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
            ]"
            :formatter="formatPhone"
          />
          <van-field
            v-model="contactForm.relationship"
            name="relationship"
            label="关系"
            placeholder="请输入与联系人关系"
            :rules="[{ required: true, message: '请输入与联系人关系' }]"
          />
        </van-cell-group>
      </van-form>
    </van-dialog>

    <!-- 头像上传 -->
    <van-uploader
      v-model="fileList"
      :after-read="afterRead"
      :before-read="beforeRead"
      v-show="false"
      ref="uploaderRef"
      accept="image/*"
      :max-size="5 * 1024 * 1024"
      @oversize="onOversize"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showSuccessToast, showConfirmDialog } from 'vant'
import { getUserProfile, updateUserProfile, uploadAvatar } from '../api'

const router = useRouter()
const userInfo = ref({})
const loading = ref(true)
const logoutLoading = ref(false)
const baseURL = import.meta.env.VITE_APP_BASE_API
const defaultAvatar = 'https://img.yzcdn.cn/vant/cat.jpeg'

// 编辑相关
const showDialog = ref(false)
const editField = ref('')
const editValue = ref('')
const showDatePicker = ref(false)

// 头像上传相关
const fileList = ref([])
const uploaderRef = ref(null)

// 日期选择器配置
const minDate = new Date(1900, 0, 1)
const maxDate = new Date()

// 血型选项
const bloodTypes = ['A型', 'B型', 'O型', 'AB型', '其他']

// 紧急联系人相关
const showContactDialog = ref(false)
const contactForm = ref({
  name: '',
  phone: '',
  relationship: ''
})

// 计算属性：性别文本
const genderText = computed(() => {
  const genderMap = {
    1: '男',
    2: '女'
  }
  return genderMap[userInfo.value.gender] || '未设置'
})

// 计算属性：对话框标题
const dialogTitle = computed(() => {
  const titles = {
    name: '姓名',
    gender: '性别',
    phone: '手机号码',
    bloodType: '血型',
    allergies: '过敏史',
    medicalHistory: '既往病史'
  }
  return titles[editField.value] || ''
})

// 加载用户信息
const loadUserInfo = async () => {
  try {
    loading.value = true
    const res = await getUserProfile()
    if (res.code === 200) {
      userInfo.value = res.data
    } else {
      showToast(res.message || '获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息失败：', error)
    showToast('获取用户信息失败')
  } finally {
    loading.value = false
  }
}

// 显示编辑弹窗
const showEditDialog = (field) => {
  editField.value = field
  editValue.value = field === 'gender' ? Number(userInfo.value[field]) : userInfo.value[field]
  showDialog.value = true
}

// 获取字段验证规则
const getFieldRules = (field) => {
  const rules = {
    name: [
      { required: true, message: '请输入姓名' },
      { pattern: /^[\u4e00-\u9fa5]{2,}$/, message: '请输入正确的中文姓名' }
    ],
    phone: [
      { required: true, message: '请输入手机号' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
    ]
  }
  return rules[field] || []
}

// 获取字段格式化函数
const getFieldFormatter = (field) => {
  const formatters = {
    phone: (val) => val.replace(/[^\d]/g, '').slice(0, 11)
  }
  return formatters[field] || ((val) => val)
}

// 处理字段失焦
const handleFieldBlur = () => {
  if (editField.value === 'phone') {
    editValue.value = editValue.value.replace(/[^\d]/g, '').slice(0, 11)
  }
}

// 处理弹窗关闭
const handleDialogClose = (action) => {
  if (action === 'confirm') {
    handleConfirmEdit()
    return false
  }
  return true
}

// 确认编辑
const handleConfirmEdit = async () => {
  try {
    // 表单验证
    const rules = getFieldRules(editField.value)
    for (const rule of rules) {
      if (rule.required && !editValue.value) {
        showToast(rule.message)
        return
      }
      if (rule.pattern && !rule.pattern.test(editValue.value)) {
        showToast(rule.message)
        return
      }
    }

    const updateData = {
      [editField.value]: editValue.value
    }
    
    const res = await updateUserProfile(updateData)
    if (res.code === 200) {
      showSuccessToast('修改成功')
      userInfo.value = {
        ...userInfo.value,
        ...updateData
      }
      showDialog.value = false
    } else {
      showToast(res.message || '修改失败')
    }
  } catch (error) {
    console.error('修改失败：', error)
    showToast('修改失败')
  }
}

// 确认日期选择
const handleDateConfirm = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const birthday = `${year}-${month}-${day}`
  
  // 更新生日
  updateUserProfile({ birthday }).then(res => {
    if (res.code === 200) {
      userInfo.value.birthday = birthday
      showSuccessToast('修改成功')
    } else {
      showToast(res.message || '修改失败')
    }
  }).catch(() => {
    showToast('修改失败')
  })
  
  showDatePicker.value = false
}

// 处理头像点击
const handleAvatarClick = () => {
  uploaderRef.value.chooseFile()
}

// 上传前校验
const beforeRead = (file) => {
  if (!['image/jpeg', 'image/png', 'image/gif'].includes(file.type)) {
    showToast('请上传 jpg、png 或 gif 格式图片')
    return false
  }
  return true
}

// 上传后处理
const afterRead = async (file) => {
  try {
    const formData = new FormData()
    formData.append('file', file.file)
    
    const res = await uploadAvatar(formData)
    if (res.code === 200) {
      userInfo.value.avatar = res.data.url
      showSuccessToast('上传成功')
    } else {
      showToast(res.message || '上传失败')
    }
  } catch (error) {
    console.error('上传失败：', error)
    showToast('上传失败')
  }
}

// 文件大小超出限制
const onOversize = () => {
  showToast('文件大小不能超过 5M')
}

// 添加紧急联系人
const handleAddContact = () => {
  contactForm.value = {
    name: '',
    phone: '',
    relationship: ''
  }
  showContactDialog.value = true
}

// 处理联系人弹窗关闭
const handleContactDialogClose = (action) => {
  if (action === 'confirm') {
    handleConfirmAddContact()
    return false
  }
  return true
}

// 确认添加紧急联系人
const handleConfirmAddContact = async () => {
  try {
    // 表单验证
    if (!contactForm.value.name) {
      showToast('请输入联系人姓名')
      return
    }
    if (!contactForm.value.phone) {
      showToast('请输入联系人手机号')
      return
    }
    if (!/^1[3-9]\d{9}$/.test(contactForm.value.phone)) {
      showToast('请输入正确的手机号')
      return
    }
    if (!contactForm.value.relationship) {
      showToast('请输入与联系人关系')
      return
    }

    const res = await updateUserProfile({
      emergencyContact: {
        ...contactForm.value,
        id: Date.now()
      }
    })
    
    if (res.code === 200) {
      if (!userInfo.value.emergencyContacts) {
        userInfo.value.emergencyContacts = []
      }
      userInfo.value.emergencyContacts.push({
        ...contactForm.value,
        id: Date.now()
      })
      showSuccessToast('添加成功')
      showContactDialog.value = false
    } else {
      showToast(res.message || '添加失败')
    }
  } catch (error) {
    console.error('添加失败：', error)
    showToast('添加失败')
  }
}

// 删除紧急联系人
const handleDeleteContact = async (id) => {
  try {
    await showConfirmDialog({
      title: '删除联系人',
      message: '确定要删除这个紧急联系人吗？',
    })
    
    const res = await updateUserProfile({
      deleteEmergencyContact: id
    })
    
    if (res.code === 200) {
      userInfo.value.emergencyContacts = userInfo.value.emergencyContacts.filter(
        contact => contact.id !== id
      )
      showSuccessToast('删除成功')
    } else {
      showToast(res.message || '删除失败')
    }
  } catch (error) {
    if (error.message !== 'cancel') {
      console.error('删除失败：', error)
      showToast('删除失败')
    }
  }
}

// 退出登录
const handleLogout = async () => {
  try {
    await showConfirmDialog({
      title: '退出登录',
      message: '确定要退出登录吗？',
    })
    
    logoutLoading.value = true
    localStorage.removeItem('token')
    router.replace('/login')
  } catch (error) {
    if (error.message !== 'cancel') {
      console.error('退出失败：', error)
      showToast('退出失败')
    }
  } finally {
    logoutLoading.value = false
  }
}

// 工具函数：掩码处理
const maskIdCard = (idCard) => {
  if (!idCard) return '未绑定'
  return idCard.replace(/^(.{6})(?:\d+)(.{4})$/, '$1********$2')
}

const maskPhone = (phone) => {
  if (!phone) return '未绑定'
  return phone.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')
}

// 格式化手机号
const formatPhone = (val) => val.replace(/[^\d]/g, '').slice(0, 11)

const handleChangePassword = () => {
  router.push('/change-password')
}

onMounted(() => {
  loadUserInfo()
})
</script>

<style lang="scss" scoped>
.profile {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-bottom: 50px;
}

.user-header {
  background-color: #fff;
  padding: 24px;
  text-align: center;
  margin-bottom: 12px;

  .avatar-wrapper {
    position: relative;
    display: inline-block;
    margin-bottom: 12px;

    .camera-icon {
      position: absolute;
      right: 0;
      bottom: 0;
      background-color: #fff;
      border-radius: 50%;
      padding: 4px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      font-size: 20px;
      color: var(--van-primary-color);
    }
  }

  .user-info {
    .name {
      font-size: 18px;
      font-weight: bold;
      color: #323233;
      margin-bottom: 4px;
    }

    .patient-no {
      font-size: 14px;
      color: #969799;
    }
  }
}

.section {
  margin-bottom: 12px;

  .section-title {
    padding: 16px;
    font-size: 16px;
    font-weight: 500;
    color: #323233;
  }

  .section-header {
    padding: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

.contact-phone {
  font-size: 14px;
  color: #969799;
}

.delete-btn {
  height: 100%;
  width: 65px;
}

.logout-wrapper {
  padding: 16px;
}

.change-password-btn {
  margin-bottom: 12px;
}

.logout-btn {
  margin-top: 0;
}

.dialog-content {
  padding: 16px;
}

:deep(.van-dialog__footer) {
  padding: 8px 16px 16px;
}

:deep(.van-field__label) {
  width: 80px;
}
</style> 